package com.rc.saas.tenant.controller.printer;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.base.BaseSearch;
import com.rc.saas.tenant.base.WebPageInfo;
import com.rc.saas.tenant.common.component.UidGenerator;
import com.rc.saas.tenant.common.utils.BeanUtil;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.model.elec.ElecStation;
import com.rc.saas.tenant.model.elec.ElecStationExample;
import com.rc.saas.tenant.model.printer.ElecPrinter;
import com.rc.saas.tenant.model.printer.ElecPrinterExample;
import com.rc.saas.tenant.model.printer.ElecPrinterStation;
import com.rc.saas.tenant.model.printer.ElecPrinterStationExample;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.service.elec.ElecStationService;
import com.rc.saas.tenant.service.printer.ElecPrinterService;
import com.rc.saas.tenant.service.printer.ElecPrinterStationService;
import com.rc.saas.tenant.shiro.ShiroUtils;
import com.rc.saas.tenant.util.ExportUtils;
import com.rc.saas.tenant.vo.elecPrinter.ElecPrinterStationResultVo;
import com.rc.saas.tenant.vo.elecPrinter.ElecPrinterSearch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;


/**
 * @author frog
 * @date 2021/8/6
 */
@Controller
@RequestMapping("/elecPrinter")
public class ElecPrinterController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ElecPrinterService elecPrinterService;

    @Autowired
    private ElecPrinterStationService elecPrinterStationService;

    @Autowired
    private ElecStationService elecStationService;

    @Autowired
    private UidGenerator uidGenerator;

    /**
     * 跳转打印机页面
     *
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index() {
        return "/templates/elecPrinter/elecPrinter";
    }

    /**
     * 返回打印机列表数据
     *
     * @return
     */
    @RequestMapping(value = "/listPageElecPrinter", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listPageElecPrinter(ElecPrinterSearch elecPrinterVO) {
        PageInfo<ElecPrinter> pageInfo = elecPrinterService.listElecPrinter(elecPrinterVO);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }


    /**
     * 保存/编辑打印机
     *
     * @return
     */
    @RequestMapping(value = "/saveOrUpdateElecPrinter", method = RequestMethod.POST)
    @ResponseBody
    public TResponse saveOrUpdateElecPrinter(ElecPrinter elecPrinter) {
        if (!BeanUtil.isValid(elecPrinter.getPrinterName(), elecPrinter.getPrinterRtua(),
                elecPrinter.getPaperRestCount(), elecPrinter.getWarnCount())) {
            return TResponse.FAIL("请输入正确的参数");
        }
        try {
            String pileRtua = uidGenerator.genPileRtua(elecPrinter.getPrinterRtua());

            ElecPrinterExample example = new ElecPrinterExample();
            example.createCriteria().andPrinterRtuaEqualTo(pileRtua);
            List<ElecPrinter> elecPrinters = elecPrinterService.selectByExample(example);

            if (elecPrinter.getPrinterId() != null) {
                elecPrinter.setPrinterRtua(null);
                elecPrinterService.updateByPrimaryKeySelective(elecPrinter);
            } else {

                if (!CollectionUtils.isEmpty(elecPrinters)) {
                    return TResponse.FAIL("已经存在逻辑地址");
                }

                if (elecPrinter.getPrinterRtua().length() > 8 || elecPrinter.getPrinterRtua().length() < 8) {
                    return TResponse.FAIL("逻辑地址为8位");
                }
                for (int i = 0; i < elecPrinter.getPrinterRtua().length(); i++) {
                    if (!Character.isDigit(elecPrinter.getPrinterRtua().charAt(i))) {
                        return TResponse.FAIL("逻辑地址为纯数字");
                    }
                }

                elecPrinter.setPrinterRtua(pileRtua);
                elecPrinter.setPrinterNo(elecPrinter.getPrinterRtua());
                elecPrinterService.insertSelective(elecPrinter);
            }
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("保存打印机失败", e);
            return TResponse.FAIL("操作失败");
        }
    }


    /**
     * 导出打印机列表
     */
    @ResponseBody
    @RequestMapping("/exportElecPrinter")
    public TResponse exportElecPrinter(ElecPrinterSearch elecPrinterVO, HttpServletResponse response) {
        response.setHeader("Set-Cookie", "fileDownload=true; path=/");
        ExportUtils.setDefaultPaging(elecPrinterVO);
        if (elecPrinterVO.getCount() == 0 || elecPrinterVO.getCount() == null) {
            elecPrinterVO.setCount(elecPrinterVO.getLimit());
        }

        //导出拼接开始条数
        elecPrinterVO.setOffset(elecPrinterVO.getLimit() * (elecPrinterVO.getOffset() - 1));
        List<ElecPrinter> list = elecPrinterService.exportElecPrinter(elecPrinterVO);

        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("打印机列表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), ElecPrinter.class).sheet("打印机列表").doWrite(list);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("导出打印机列表失败", e.getMessage());
            return TResponse.FAIL(e.getMessage());
        }
    }


    /**
     * 跳转打印机站点页面
     *
     * @return
     */
    @RequestMapping(value = "/elecPrinterStation/{printerId}", method = RequestMethod.GET)
    public String elecPrinterStation(@PathVariable("printerId") Long printerId, Model model) {
        ElecPrinter elecPrinter = elecPrinterService.selectByPrimaryKey(printerId);

        TenantUser user = ShiroUtils.getSessionUser();
        ElecStationExample elecStationExample = new ElecStationExample();
        elecStationExample.createCriteria().andTenantCodeEqualTo(user.getTenantCode()).andHlhtOperatorIdIsNull().andHlhtStationNoIsNull();
        List<ElecStation> elecStations = elecStationService.selectByExample(elecStationExample);
        model.addAttribute("elecStations", elecStations);
      //  ElecPrinterStationExample printerStationExample = new ElecPrinterStationExample();
      //  printerStationExample.createCriteria().andPrinterIdEqualTo(printerId);
      //  List<ElecPrinterStation> elecPrinterStations = elecPrinterStationService.selectByExample(printerStationExample);
//
      //  if (!CollectionUtils.isEmpty(elecStations)) {
      //      if (CollectionUtils.isEmpty(elecPrinterStations)) {
      //          model.addAttribute("elecStations", elecStations);
      //      } else {
      //          Iterator<ElecStation> it = elecStations.iterator();
      //          while (it.hasNext()) {
      //              ElecStation x = it.next();
      //              for (ElecPrinterStation elecPrinterStation : elecPrinterStations) {
      //                  if (elecPrinterStation.getElecStationId().equals(x.getElecStationId())) {
      //                      it.remove();
      //                  }
      //              }
      //          }
      //          model.addAttribute("elecStations", elecStations);
      //      }
//
      //  }
        model.addAttribute("elecPrinter", elecPrinter);
        return "/templates/elecPrinter/elecPrinterStation";
    }


    /**
     * 返回打印机站点列表数据
     *
     * @return
     */
    @RequestMapping(value = "/listPageElecPrinterStation", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listPageElecPrinterStation(BaseSearch baseSearch, Long printerId) {
        PageInfo<ElecPrinterStationResultVo> pageInfo = elecPrinterStationService.listPageElecPrinterStation(baseSearch, printerId);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }


    /**
     * 保存打印机站点
     *
     * @return
     */
    @RequestMapping(value = "/saveElecPrinterStation", method = RequestMethod.POST)
    @ResponseBody
    public TResponse saveElecPrinterStation(Long elecStationId, Long printerId) {
        if (!BeanUtil.isValid(elecStationId, printerId)) {
            return TResponse.FAIL("请输入正确的参数");
        }
        try {

            ElecStation elecStation = elecStationService.selectByPrimaryKey(elecStationId);
            if (elecStation == null) {
                return TResponse.FAIL("不存在此桩群");
            }

            ElecPrinterStationExample elecPrinterStationExample = new ElecPrinterStationExample();
            elecPrinterStationExample.createCriteria().andElecStationIdEqualTo(elecStationId)
                    .andPrinterIdEqualTo(printerId);
            List<ElecPrinterStation> elecPrinterStations = elecPrinterStationService.selectByExample(elecPrinterStationExample);
            if (!CollectionUtils.isEmpty(elecPrinterStations)) {
                return TResponse.FAIL("此桩群已绑定过此打印机");
            }

            ElecPrinterStation elecPrinterStation = new ElecPrinterStation();
            elecPrinterStation.setPrinterId(printerId);
            elecPrinterStation.setElecStationId(elecStationId);
            elecPrinterStationService.insertSelective(elecPrinterStation);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("保存打印机站点失败", e);
            return TResponse.FAIL("操作失败");
        }
    }


    /**
     * 更改打印机站点状态
     *
     * @return
     */
    @RequestMapping(value = "/updateStatus", method = RequestMethod.POST)
    @ResponseBody
    public TResponse updateStatus(Long printerStationId) {
        try {
            ElecPrinterStation elecPrinterStation = elecPrinterStationService.selectByPrimaryKey(printerStationId);
            if ("0".equals(elecPrinterStation.getStatus())) {
                elecPrinterStation.setStatus("1");
            } else if ("1".equals(elecPrinterStation.getStatus())) {
                elecPrinterStation.setStatus("0");
            }
            elecPrinterStationService.updateByPrimaryKeySelective(elecPrinterStation);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("更改打印机站点状态失败", e);
            return TResponse.FAIL("操作失败");
        }
    }
}
